package com.work.customer.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.work.customer.dao.CustUserMapper;
import com.work.customer.pojo.CustUser;
import com.work.customer.service.CustUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Map;

@Service
@Transactional
public class CustUserServiceImpl implements CustUserService {

    @Autowired
    private CustUserMapper custUserMapper;


    //通过农场id查询超级管理员
    @Override
    public CustUser findByCustomerId(Integer id) {
        return custUserMapper.findByCustomerId(id);
    }

    //更新超级管理员信息
    @Override
    public void update(CustUser custUser) {
        custUserMapper.updateByPrimaryKeySelective(custUser);
    }

    //多条件分页查询
    @Override
    public Page<CustUser> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<CustUser>)custUserMapper.selectByExample(example);
    }

    @Override
    public CustUser findById(Integer id) {
        return custUserMapper.selectByPrimaryKey(id);
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(CustUser.class);
        Example.Criteria criteria = example.createCriteria();
            if (searchMap != null) {

                // 用户名
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    criteria.andLike("name", "%" + searchMap.get("name") + "%");
                }

                // 登录名
                if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                    criteria.andLike("username", "%" + searchMap.get("username") + "%");
                }

                // 状态 0-停用，1-启用
                if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                    criteria.andEqualTo("status", searchMap.get("status"));
                }

            }
            criteria.andEqualTo("level", "1");
        return example;
    }

}
